import React, { Component } from 'react';
import { View, Text, TouchableOpacity, TextInput, ListView, StyleSheet, Platform, Dimensions, KeyboardAvoidingView, Alert, ScrollView } from 'react-native';
import { SwipeListView } from 'react-native-swipe-list-view';
import api from '../../utils/api';
import constants from '../../utils/constants';
import moment from 'moment';
import Iconfont from "../home/icon/iconfont";


const screen = Dimensions.get("screen");

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
        position: "relative"
    },
    dateItem: {
        alignItems: 'center',
        paddingTop: 5,
        paddingBottom: 15
    },
    dateItemActive: {
        //backgroundColor: constants.themeColor,
        alignItems: 'center',
        paddingTop: 5,
        paddingBottom: 15,

    },
    dateItemText: {
        color: "#B8B8B8"
    },
    dateItemActiveText: {
        color: "#fff"
    },
    taskListBox: {
        borderColor: "#cccccc",
        borderWidth: 1,
        fontSize: 12,
        width: 20,
        height: 20,
        textAlign: "center",
        alignItems: "center",
        justifyContent: "center",
        marginTop: 1,
        color: "#ccc"
    },
    taskListItemName: {
        fontSize: 16,
        color: "#292B4D",
        // marginLeft: 5
    },
    buttomBtnView: {
        position: "absolute",
        bottom: Platform.OS === 'android' ? 15 : 15,
        alignItems: "center",
        justifyContent: "center",
        flexDirection: "row",
        width: "100%",

    },
    addTaskView: {
        backgroundColor: "#fff",
        borderBottomWidth: 1,
        borderColor: "#ddd",
        height: 65,
        bottom: Platform.OS === 'android' ? 0 : 0,



    },
    addTaskViewTextInput: {
        width: "100%",
        height: 65,
        paddingLeft: 50,
        fontSize: 16
    },
    buttomBtn: {
        borderRadius: 15,
        width: 120,
        height: 38,
        backgroundColor: "#fff"

    },
    standalone: {
        marginTop: 30,
        marginBottom: 30,
    },
    standaloneRowFront: {
        alignItems: 'center',
        backgroundColor: '#CCC',
        justifyContent: 'center',
        height: 50,
    },
    standaloneRowBack: {
        alignItems: 'center',
        backgroundColor: '#8BC645',
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'space-between',
        padding: 15
    },
    backTextWhite: {
        color: '#FFF'
    },
    rowFront: {

        alignItems: 'center',
        backgroundColor: '#ffffff',
        borderBottomColor: '#ddd',
        borderBottomWidth: 1,
        height: 55,
        flexDirection: "row",
        // paddingLeft: 20
    },
    rowBack: {
        alignItems: 'center',
        backgroundColor: "transparent",
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'space-between',
        paddingLeft: 15,
        borderBottomColor: '#ddd',
        borderBottomWidth: 1,
    },
    backRightBtn: {
        alignItems: 'center',
        bottom: 0,
        justifyContent: 'center',
        position: 'absolute',
        top: 0,
        width: 75
    },
    backRightBtnLeft: {
        backgroundColor: 'blue',
        right: 75
    },
    backRightBtnRight: {
        backgroundColor: constants.activeColor,
        right: 0
    },
    controls: {
        alignItems: 'center',
        marginBottom: 30
    },
    switchContainer: {
        flexDirection: 'row',
        justifyContent: 'center',
        marginBottom: 5
    },
    switch: {
        alignItems: 'center',
        borderWidth: 1,
        borderColor: 'black',
        paddingVertical: 10,
        width: Dimensions.get('window').width / 4,
    },
    trash: {
        height: 25,
        width: 25,
    },
    calendarBox: {
        elevation: 5
    }
});

export default class TaskDetail extends Component {


    static navigationOptions = (e) => {
        return {
            title: "任务详情"
        }
    }

    state = {
        task: {
            subTaskVoList: []
        },
        subTaskTitle: ""
    }

    constructor(props) {
        super(props);
        this.ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
    }




    componentDidMount() {

        this.loadTask();
    }

    loadTask = () => {
        const { getParam } = this.props.navigation;

        api({
            url: "/task/v2/info?taskId=" + getParam("id"),
            method: "POST"
        }).then(data => {
            this.setState({
                task: data.result,
                subTaskTitle: ""
            })
        })
    }

    //添加任务
    onUpdateTaskSubmitEditing = (e) => {
        const text = e.nativeEvent.text;
        if (text) {


        }
    }

    onAddTaskSubmitEditing = (e) => {
        const { task } = this.state;
        const text = e.nativeEvent.text;
        if (text) {
            api({
                url: "/task/sub/add",
                method: "POST",
                body: {
                    taskName: text,
                    status: 0,
                    taskId: task.taskId
                }
            }).then(data => {
                this.loadTask();
                this.realoadStudy();
            })

        }
    }

    /**
     * 完成任务
     */
    onTaskBoxClick = (data, index, status) => {

        const { task } = this.state;

        // const list = this.state[name];
        task.subTaskVoList[index]["status"] = status == 1 ? 0 : 1;

        this.setState({
            task: task
        });


        api({
            url: "/task/sub/sign",
            method: "POST",
            body: {
                sign: status == 1 ? 0 : 1,
                subTaskId: data.subTaskId
            }
        }).then(data => {
            this.loadTask();
            this.realoadStudy();
        })

    }

    realoadStudy = () => {
        const { getParam } = this.props.navigation;
        getParam("backStudy", () => { })();
    }

    /**
   * 删除任务
   */
    removeTask = (data, rowId) => {
        const { task } = this.state;

        // taskService.remove(data.id);
        Alert.alert("提示", "是否删除该任务?", [
            { text: "取消" },
            {
                text: "确定", onPress: () => {
                    console.log("data:", data, rowId);
                    task.subTaskVoList.splice(rowId, 1);
                    this.setState({
                        task: task
                    });

                    api({
                        url: "/task/sub/delete?subTaskId=" + data.subTaskId,
                        method: "POST"
                    }).then(data => {
                        this.loadTask();
                        this.realoadStudy();
                    })


                }
            },

        ], { cancelable: true })

    }


    render() {
        const { task } = this.state;
        return (
            <View>
                <KeyboardAvoidingView behavior="position" keyboardVerticalOffset={64}>
                    <ScrollView

                        // keyboardDismissMode="on-drag"
                        // keyboardShouldPersistTaps="always"
                        keyboardShouldPersistTaps={"handled"}
                        keyboardDismissMode={"interactive"}
                    >


                        <View style={{ height: 55, flexDirection: "row", marginTop: 0, }}>
                            <View style={{ justifyContent: "center", height: 55, width: 40, alignItems: "center" }}>
                                {/* <TouchableOpacity style={[{
                                borderWidth: 1,
                                borderColor: task.status == 0 ? "#ddd" : constants.activeColor,
                                alignItems: "center",
                                justifyContent: "center",
                                width: 20,
                                height: 20,
                            }]}>
                                <Text style={{ color: task.status == 0 ? "#ddd" : constants.activeColor }}>√</Text>
                            </TouchableOpacity> */}
                                <Iconfont name="check-box" size={20} color={task.status == 0 ? "#ddd" : constants.activeColor}></Iconfont>
                            </View>

                            <View style={{ justifyContent: "center", height: 55 }}>
                                <TextInput
                                    onSubmitEditing={(e) => {
                                        const text = e.nativeEvent.text;
                                        if (text) {
                                            api({
                                                url: "/task/v2/update",
                                                method: "POST",
                                                body: {
                                                    taskId: task.taskId,
                                                    taskName: text
                                                }
                                            }).then(data => {

                                                this.realoadStudy();
                                            });
                                        } else {
                                            this.loadTask();
                                        }
                                    }}
                                    autoFocus={false}
                                    returnKeyLabel={"确定"}
                                    returnKeyType={"done"}
                                    placeholderTextColor={"#ccc"}
                                    onChangeText={(text) => {

                                        task.taskName = text;
                                        this.setState({
                                            task: task
                                        })
                                    }}
                                    value={task.taskName}
                                    style={[{ color: constants.themeColor, fontSize: 16, fontWeight: "bold", width: "100%", marginLeft: 10 }]}
                                    placeholder={""}>
                                </TextInput>
                                {/* <Text style={{ color: constants.themeColor, fontSize: 16, fontWeight: "bold" }}>{task.taskName}</Text> */}
                            </View>

                        </View>
                        <View style={{ borderBottomColor: "#ddd", borderBottomWidth: 1, height: 55, justifyContent: "center" }}>
                            <TextInput
                                onSubmitEditing={(e) => {
                                    const text = e.nativeEvent.text;
                                    if (text) {
                                        api({
                                            url: "/task/v2/update",
                                            method: "POST",
                                            body: {
                                                taskId: task.taskId,
                                                des: text
                                            }
                                        }).then(data => {

                                            this.realoadStudy();
                                        })
                                    } else {
                                        this.loadTask();
                                    }
                                }}
                                onChangeText={(text) => {
                                    task.des = text;
                                    this.setState({
                                        task: task
                                    });
                                }}
                                autoFocus={false}
                                returnKeyLabel={"确定"}
                                returnKeyType={"done"}
                                placeholderTextColor={"#ccc"}
                                value={task.des}
                                style={[{ marginLeft: 50, color: "#ccc" }]}
                                placeholder={"点击添加描述"}>
                            </TextInput>
                        </View>
                        <View>

                            <SwipeListView
                                enableEmptySections={true}
                                dataSource={this.ds.cloneWithRows(task.subTaskVoList)}
                                renderRow={((data, secId, rowId, rowMap) => (
                                    <View style={styles.rowFront}>
                                        <View style={{ width: 35, justifyContent: "center", marginLeft: 50 }}>
                                            <TouchableOpacity onPress={() => {
                                                this.onTaskBoxClick(data, rowId, data.status);
                                            }}>

                                                {/* <View style={[styles.taskListBox, { borderColor: data.status == 0 ? "#ddd" : constants.activeColor }]}>
                                                    <Text style={{ color: data.status == 0 ? "#ddd" : constants.activeColor }}>√</Text>
                                                </View> */}
                                                <Iconfont name="check-box" size={20} color={data.status == 0 ? "#ddd" : constants.activeColor}></Iconfont>
                                            </TouchableOpacity>
                                        </View>

                                        <View style={{
                                            // borderBottomColor: "#ddd",
                                            // borderBottomWidth: 1,
                                            width: (screen.width - 50),
                                            height: 55,
                                            justifyContent: "center"
                                        }}


                                        >

                                            <TextInput
                                                onSubmitEditing={(e) => {
                                                    const text = e.nativeEvent.text;
                                                    if (text) {
                                                        api({
                                                            url: "/task/sub/update",
                                                            method: "POST",
                                                            body: {
                                                                subTaskId: data["subTaskId"],
                                                                taskName: text
                                                            }
                                                        }).then(data => {
                                                            this.loadTask();
                                                            //this.realoadStudy();
                                                        })
                                                    }

                                                }}
                                                autoFocus={false}
                                                returnKeyLabel={"确定"}
                                                returnKeyType={"done"}
                                                placeholderTextColor={"#ccc"}
                                                style={[{ width: "100%" }]}
                                                value={data.taskName}
                                                onChangeText={(text) => {
                                                    task.subTaskVoList[rowId]["taskName"] = text;
                                                    this.setState({
                                                        task: task
                                                    })
                                                }}

                                            >
                                            </TextInput>

                                            {/* <Text
                                            // onPress={() => {
                                            //     appNavigation.navigate("TaskDetail", { id: data.taskId });
                                            // }}
                                            style={[
                                                styles.taskListItemName,
                                                data.status === 1 ? { color: "#292B4D" } : {}
                                            ]}
                                        >
                                            {data.taskName}
                                        </Text> */}
                                        </View>

                                    </View>
                                ))}
                                renderHiddenRow={(data, secId, rowId, rowMap) => {
                                    const rowKey = `${secId}${rowId}`;
                                    return (
                                        <View style={styles.rowBack}>
                                            <TouchableOpacity style={[styles.backRightBtn, styles.backRightBtnRight]} onPress={() => {
                                                // console.log("rowMap::",rowMap);
                                                // console.log("role::",rowMap[rowKey]);
                                                const row = rowMap[rowKey];
                                                if (row) {
                                                    row.closeRow();
                                                }
                                                this.removeTask(data, rowId)
                                            }}>
                                                <Text style={styles.backTextWhite}>删除</Text>
                                            </TouchableOpacity>
                                        </View>
                                    );
                                }}
                                renderFooter={() => {
                                    return (
                                        <View style={[styles.rowFront, { borderBottomWidth: 1, borderColor: "#ddd", flex: 1 }]}>
                                            {/* <Text style={{ width: "100%", fontSize: 16, color: "#ccc" }} >
                                        添加新任务...
                                    </Text> */}

                                            <TextInput
                                                onSubmitEditing={this.onAddTaskSubmitEditing.bind(this)}
                                                autoFocus={false}
                                                returnKeyLabel={"确定"}
                                                returnKeyType={"done"}
                                                placeholderTextColor={"#ccc"}
                                                style={[{ marginLeft: 50,  }]}
                                                value={this.state.subTaskTitle}
                                                onChangeText={(text) => {
                                                    this.setState({
                                                        subTaskTitle: text
                                                    })
                                                }}
                                                placeholder={"点击添加子项目"}>
                                            </TextInput>

                                        </View>
                                    )
                                }}
                                rightOpenValue={-75}
                                disableRightSwipe={true}
                               



                            >

                            </SwipeListView>


                        </View>
                    </ScrollView>
                </KeyboardAvoidingView>
            </View>
        )
    }
}